'use strict';

const downloadModel = require('../models/download_log.model')
const Code = require('../common/error_code');
const send = require('koa-send')
const path = require('path')
/**
 * 获取下载列表
 * @returns {Promise.<void>}
 */
async function getDownloadFilePath(ctx){
    let rst = await downloadModel.find({},{download_time:1,log_path:1,file_name:1,download_current:1,download_total:1,download_statue:1}).sort({download_time:-1})
    // console.log(rst)
    // console.log(rst.length)
    // let data = []
    // for(let item in rst){
    //     data.push({
    //
    //     })
    // }
    ctx.success(Code.RET_DWONLOAD_OK,rst)
}

async function startDownloadFile (ctx) {
    let params = ctx.request.query;
    let filepath = params.path
    if(!path){
        ctx.error(Code.RET_DWONLOAD_ERR_PARAMS_DOWNLOAD)
        return
    }
    let filename = path.basename(filepath)
    let fileDir = path.dirname(filepath)
    let downloadfileName = params.name || filename
    console.log(filepath)
    await send(ctx, filename, {root:fileDir,
        setHeaders: (res, path, stats) => {
            res.setHeader('Content-Disposition', 'attachment;filename=' + downloadfileName)
        }
    })
}

exports.getDownloadFilePath = getDownloadFilePath
exports.startDownloadFile = startDownloadFile